<template>
  <div class="type-select">
    <el-select v-model="level1" style="width: 100%" placeholder=" " @change="change1">
      <el-option v-for="item in typeTree" :label="item.code + ' ' + item.title" :value="item.id">
      </el-option>
    </el-select>
    <el-select v-model="level2" style="width: 100%" placeholder=" " @change="change2">
      <el-option v-for="item in level2List" :label="item.code + ' ' + item.title" :value="item.id">
      </el-option>
    </el-select>
    <el-select v-model="value" style="width: 100%" placeholder=" ">
      <el-option v-for="item in level3List" :label="item.code + ' ' + item.title" :value="item.id">
      </el-option>
    </el-select>
  </div>
</template>

<script>
import {defineProps, defineEmits} from 'vue'
import $api from "../api";

export default {
  name: 'TypeSelect',
  props: {
    modelValue: {
      type: Number,
      default: null
    }
  },
  computed: {
    value: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
      }
    }
  },
  data() {
    return {
      listLoading: true,
      typeTree: [],
      level1: null,
      level2: null,
      level2List: [],
      level3List: []
    }
  },
  mounted() {
    this.getListTree()
  },
  methods: {
    change1: function (id) {
      this.level2 = ''
      this.$emit('update:modelValue', null)
      this.level2List = []
      this.level3List = []
      this.typeTree.forEach(level1 => {
        if (level1.id === id) {
          this.level2List = level1.children
        }
      })
    },
    change2: function (id) {
      this.level3List = []
      this.$emit('update:modelValue', null)
      this.level2List.forEach(level2 => {
        if (level2.id === id) {
          this.level3List = level2.children
        }
      })
    },
    getListTree: function () {
      var that = this
      $api.typeApi.listTree().then(res => {
        that.typeTree = res
        this.setOptions()
        that.listLoading = false
      }).catch(() => {
        that.listLoading = false
      })
    },
    setOptions() {
      if (this.modelValue) {
        this.typeTree.forEach(level1 => {
          level1.children.forEach(level2 => {
            level2.children.forEach(level3 => {
              console.log(level3.id, this.modelValue)
              if (level3.id === this.modelValue) {
                this.level1 = level1.id
                this.level2 = level2.id
                this.level2List = level1.children
                this.level3List = level2.children
              }
            })
          })
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.type-select {
  display: flex;
}
</style>